package com.why.blog.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**自定义
 * @program: blog
 * @description:记录管理异常并作出处理
 * @author: @why
 * @create: 2021-01-15 20:50
 **/
@Slf4j
@ControllerAdvice
public class LogExceptionMssager {

    /**
     * 进行全局的异常处理，记录到日志当中，如果发现有被注解ResponseStatus标注的，则抛出交给springboot去处理
     *
     * @param request
     * @param ex
     * @return
     * @throws Exception
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView ControllerHanlder(HttpServletRequest request, Exception ex) throws Exception {

        log.error("error of url and message:{},Exception:{}", request.getRequestURL(), ex);

        if (AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class) != null) {
            throw ex;
        }

        ModelAndView model = new ModelAndView();
        model.setViewName("/error/500");
        return model;

    }

}
